<template>
  <div class="container">
    <div class="flex_js">
      <el-form>
        <div class="flex" style="gap: 20px">
          <el-form-item label="类型">
            <el-select v-model="page_data.typeId" clearable>
              <el-option
                v-for="item in type_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称">
            <el-input
              style="width: 200px"
              v-model="page_data.name"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <div class="flex">
            <el-button type="primary" @click="get_list()">查询</el-button>
            <el-button @click="(page_data.typeId = ''), (page_data.name = '');"
              >重置</el-button
            >
          </div>
        </div>
      </el-form>
      <div class="flex">
        <el-button
          type="primary"
          @click="show_add_box = true"
          v-if="has_role_list[3].has_role"
          >新增大样图</el-button
        >
        <el-button
          type="primary"
          @click="show_type_page = true"
          v-if="has_role_list[5].has_role"
          >类型管理</el-button
        >
      </div>
    </div>
    <el-table :data="list" class="tc" border :max-height="max_height">
      <el-table-column label="类型" sortable prop="typeId">
        <template #default="scope: any">
          <div v-for="item in type_list" :key="item.id">
            <span v-if="scope.row.drawingTypeId == item.id">{{ item.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" sortable> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope: any">
          <div class="flex_cc" style="column-gap: 20px">
            <el-tooltip
              v-if="has_role_list[1].has_role"
              content="编辑"
              placement="bottom"
            >
              <svgBtn
                icon="table_edit"
                style="font-size: 20px"
                @click="edit_list({ item: scope.row, type: 1 })"
              ></svgBtn>
            </el-tooltip>
            <el-tooltip
              v-if="has_role_list[4].has_role && scope.$index != 0"
              content="上移"
              placement="bottom"
            >
              <svgBtn
                icon="table_move"
                style="font-size: 20px"
                @click="edit_list({ item: scope.row, type: 2 })"
              ></svgBtn>
            </el-tooltip>
            <el-tooltip
              v-if="has_role_list[4].has_role && scope.$index < list.length - 1"
              content="下移"
              placement="bottom"
            >
              <svgBtn
                icon="table_move"
                style="font-size: 20px; transform: rotate(180deg)"
                @click="edit_list({ item: scope.row, type: 3 })"
              ></svgBtn>
            </el-tooltip>
            <el-tooltip
              v-if="has_role_list[2].has_role"
              content="删除"
              placement="bottom"
            >
              <svgBtn
                icon="table_delete"
                style="font-size: 20px"
                @click="edit_list({ item: scope.row, type: 4 })"
              ></svgBtn>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer
      v-model="show_add_box"
      direction="rtl"
      size="30%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(addBigImgForm)"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增</h4>
        <h4 v-else>编辑</h4>
      </template>
      <template #default>
        <el-form
          ref="addBigImgForm"
          :model="add_form_data"
          :rules="rules"
          label-width="150px"
        >
          <el-form-item label="类型" prop="typeId">
            <el-select v-model="add_form_data.typeId">
              <el-option
                v-for="item in type_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="大样附图(DWG)" prop="detailDrawing">
            <upload
              :imageUrl="add_form_data.detailDrawing"
              :width="100"
              :height="100"
              :limit="1"
              :uploadUrl="serviceApi.upload_drawing"
              :accept="'dwg'"
              :fileNames="['大样附图']"
            ></upload>
          </el-form-item>
          <el-form-item label="预览图" prop="preview">
            <upload
              :imageUrl="add_form_data.preview"
              :width="100"
              :height="100"
              :limit="1"
              :uploadUrl="serviceApi.upload_drawing"
              :downloadUrl="serviceApi.download_drawing"
              :accept="'image/jpeg,image/jpg,image/png'"
              :fileNames="['预览图']"
            ></upload>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addBigImgForm)">取消</el-button>
            <el-button type="primary" @click="submit(addBigImgForm)">确定</el-button>
          </div>
        </el-form>
      </template>
    </el-drawer>
    <type_page
      :show_type_page="show_type_page"
      :type="'1'"
      @close="show_type_page = false"
    ></type_page>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from "@/utils/check_role";
import svgBtn from "@/components/svg_button.vue";
import { ref, onMounted, onUnmounted, reactive, watch } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import upload from "@/view/components/upload.vue";
import type_page from "./type.vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import EventBus from "@/utils/EventBus";
const has_role_list = ref([
  { path: "", has_role: false },
  { path: "/drawing/put", has_role: false },
  { path: "/drawing/delete", has_role: false },
  { path: "/drawing/post", has_role: false },
  { path: "/drawing/move", has_role: false },
  { path: "/drawingType", has_role: false },
]);
// type FormInstance = InstanceType<typeof ElForm>
const addBigImgForm = ref<FormInstance>();
const detailDrawingUpload = (rule, value, callback) => {
  if (!add_form_data.value.detailDrawing.length) {
    callback(new Error("请上传大样附图"));
  } else {
    callback();
  }
};
const previewUpload = (rule, value, callback) => {
  if (!add_form_data.value.preview.length) {
    callback(new Error("请上传预览图"));
  } else {
    callback();
  }
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入大样图名称", trigger: "blur" }],
  typeId: [{ required: true, message: "请选择大样图类型", trigger: "change" }],
  detailDrawing: [
    {
      validator: detailDrawingUpload,
      required: true,
    },
  ],
  preview: [
    {
      validator: previewUpload,
      required: true,
    },
  ],
});
const page_data = ref({ name: "", typeId: "", type: 1 });
const show_add_box = ref(false);
const show_type_page = ref(false);
const add_form_data = ref({
  name: "",
  typeId: "",
  detailDrawing: [],
  preview: [],
  id: "",
  type: "1",
});
const edit_list = (e) => {
  if (e.type == 1) {
    add_form_data.value = {
      name: e.item.name,
      typeId: e.item.drawingTypeId,
      detailDrawing:
        e.item.detailDrawing.split("/").length == 3
          ? [
              e.item.detailDrawing.split("/")[1] +
                "/" +
                e.item.detailDrawing.split("/")[2],
            ]
          : [e.item.detailDrawing],
      preview:
        e.item.preview.split("/").length == 3
          ? [e.item.preview.split("/")[1] + "/" + e.item.preview.split("/")[2]]
          : [e.item.preview],
      id: e.item.id,
      type: "1",
    };
    show_add_box.value = true;
  } else if (e.type == 4) {
    ElMessageBox.confirm("确定删除图样 - " + e.item.name + " ?", "", {
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      closeOnClickModal: false,
      type: "warning",
    }).then(() => {
      axios
        .request({
          url: serviceApi.drawing_curd + "/" + e.item.id,
          method: "delete",
        })
        .then(() => {
          ElMessage.success("操作成功！");
          setTimeout(() => {
            get_list();
          }, 1000);
        })
        .catch((err) => {
          ElMessage.error(err);
        });
    });
  } else if ([2, 3].includes(e.type)) {
    axios
      .request({
        url:
          e.type == 2 ? serviceApi.drawing_moveUpSort : serviceApi.drawing_moveDownSort,
        method: "put",
        params: { id: e.item.id },
      })
      .then(() => {
        ElMessage.success("操作成功！");
        setTimeout(() => {
          get_list();
        }, 1000);
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  }
};
const submit = async (formEl: FormInstance | undefined) => {
  console.log(
    add_form_data.value.detailDrawing,
    add_form_data.value.detailDrawing.length
  );
  await formEl.validate((valid) => {
    console.log(valid, add_form_data.value);
    if (valid) {
      let data = JSON.parse(JSON.stringify(add_form_data.value));
      data.detailDrawing = data.detailDrawing.toString();
      data.preview = data.preview.toString();
      axios
        .request({
          url:
            data.id == ""
              ? serviceApi.drawing_curd
              : serviceApi.drawing_curd + "/" + data.id,
          method: data.id == "" ? "post" : "put",
          data: data,
        })
        .then(() => {
          ElMessage.success("操作成功！");
          setTimeout(() => {
            resetForm(formEl);
            get_list();
          }, 1000);
        })
        .catch((err) => {
          ElMessage.error(err);
        });
    }
  });
};
const max_height = ref();
onMounted(() => {
  max_height.value = window.innerHeight - 350;
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  get_list();
  get_type_list();
  EventBus.on("change_type_list", () => {
    get_type_list();
  });
  // 上传成功 （取消） 验证提示
  EventBus.on("upload_succ", () => {
    add_form_data.value.detailDrawing.length
      ? addBigImgForm.value.validateField("detailDrawing")
      : "";
    add_form_data.value.preview.length
      ? addBigImgForm.value.validateField("preview")
      : "";
  });
});
onUnmounted(() => {
  EventBus.off("change_type_list");
});
const list = ref();
const type_list = ref();
const get_list = () => {
  axios
    .request({
      url: serviceApi.drawing_list,
      method: "post",
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res);
      list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const get_type_list = () => {
  axios
    .request({
      url: serviceApi.drawingType_list,
      method: "post",
      data: handle_search_key({ type: "1" }),
    })
    .then((res) => {
      console.log(res);
      type_list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    name: "",
    typeId: "",
    detailDrawing: [],
    preview: [],
    id: "",
    type: "1",
  };
  show_add_box.value = false;
};
</script>

<style lang="scss" scoped></style>
